package main

import (
	"crypto/rand"
	"encoding/json"
	"fmt"
	"io/ioutil"
	"net/http"
	"os"
	response2 "response"
	"strings"
)

func main() {
	args := os.Args
	if args == nil || len(args) < 2 {
		Usage()
		return
	}
	dependencyTemplate := "<dependency>\n" +
		"	<groupId>%s</groupId>\n" +
		"	<artifactId>%s</artifactId>\n" +
		"    <version>%s</version>\n" +
		"</dependency>"
	param := strings.Join(args[1:],"%20")
	client := &http.Client{}
	request, _ := http.NewRequest("GET", "https://search.maven.org/solrsearch/select?q="+param+"&start=0&rows=20", nil)
	response, err := client.Do(request)
	if err != nil {
		fmt.Println(err)
	}

	if response.StatusCode != 200 {
		os.Exit(1)
	}
	body, _ := ioutil.ReadAll(response.Body)
	f :=make(map[string]interface{})
	err = json.Unmarshal(body, &f)
	if err != nil {
		fmt.Println(err)
	}
	responseJson:=f["response"].(map[string]interface{})["docs"]
	//data:=f["response"].([]interface{})[3]
	i := 0
	var mavenInfos []response2.Maven
	for {
		if i >= 20 {
			break
		}
		maven:=&response2.Maven{}
		maven.SetProperties(responseJson.([]interface{})[i].(map[string]interface{})["a"].(string),responseJson.([]interface{})[i].(map[string]interface{})["g"].(string),responseJson.([]interface{})[i].(map[string]interface{})["latestVersion"].(string))
		mavenInfos=append(mavenInfos, *maven)
		i++
	}
	var result response2.Response
	var infos []response2.Info
	for _, n := range mavenInfos {
		info := &response2.Info{}
		icon := response2.Icon{IType: "fileicon", Path: "~/Desktop"}
		info.SetProperties(GetUID(), "text", n.GroupId+"-"+n.ArtifactId, "groupId:"+n.GroupId+" artifactId:"+n.ArtifactId+" version:"+n.LatestVersion, fmt.Sprintf(dependencyTemplate, n.GroupId, n.ArtifactId, n.LatestVersion), "false", icon)
		//info.SetProperties(GetUID(),"text",param,"groupId:"+"ssss"+" artifactId:"+"ssss"+" version:"+"ssss","sssssssssssss","false",icon)
		infos = append(infos, *info)
	}
	result.Items = infos
	json, _ := json.Marshal(result)
	fmt.Println(string(json))
}

var Usage = func() {
	fmt.Println("input param")
}

var strstr = []byte("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ")

func GetUID() string {
	data := make([]byte, 16)
	_, err := rand.Read(data)
	if err != nil {
		panic(err)
	}
	uuid := fmt.Sprintf("%X-%X-%X-%X-%X", data[0:4], data[4:6], data[6:8], data[8:10], data[10:])
	return uuid
}
